<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/20
 * Time: 下午5:26
 */

namespace App\Console\Commands;

use App\Modules\Agent\Services\AgentServices;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Channel\Models\Channel;
use App\Modules\Channel\Models\ChannelUser;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Statistic\SendStatsEmailService;
use App\Modules\Trade\Services\OrderService;
use App\Modules\User\Services\UserService;
use App\Modules\Util;
use DB;
use Illuminate\Console\Command;
use Log;

class SendOrderDailyDataEmail extends Command
{
    /**
     * 执行命令 获取站点的派单数据及服务号信息
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send_order_data_email';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送邮件信息';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date = date('Y-m-d', strtotime('-1 day'));
        $this->sendSendOrderDailyDataEmail($date);
    }

    function sendSendOrderDailyDataEmail($date)
    {
        //微信内
        $distribution_channel_ids = explode(',', env('INNER_CHANNEL_ID_LIST'));
        $promotion_type = 'EXTERNAL';
        $end_time = date('Y-m-d');
        $start_time = date('Y-m-01');
        $params = compact('distribution_channel_ids', 'start_time', 'end_time', 'promotion_type');
        $data = SendOrderService::searchForDaliy($params, true);

        $month = date('m');
        $content = "<strong>追书云推广：</strong> <br/><strong>微信内：</strong><br/>" . $month . "月推广合计：";
        $content .= $this->getMonthTotalInfo($month, $data);

        $content .= "<br/> 近三天数据：<br/>";
        $params['start_time'] = date('Y-m-d ', strtotime('-3 day'));
        $data = SendOrderService::searchForDaliy($params, true);
        $content .= $this->getDaliyInfo($data);

        $content .= "<br/><strong>信息流推广：</strong><br/>" . $month . "月推广合计：";
        //信息流
        $distribution_channel_ids = explode(',', env('OUT_CHANNEL_ID_LIST_SEND_ORDER'));
        $end_time = date('Y-m-d H:i:s');
        $start_time = date('Y-m-01');
        $params = compact('distribution_channel_ids', 'start_time', 'end_time', 'promotion_type');
        $data = SendOrderService::searchForDaliy($params, true);
        $content .= $this->getMonthTotalInfo($month, $data);

        foreach ($distribution_channel_ids as $distribution_channel_id) {
            $end_time = date('Y-m-d', strtotime('-3 day'));
            $start_time = date('Y-m-d', strtotime('-7 day'));
            $params = compact('distribution_channel_id', 'start_time', 'end_time', 'promotion_type');
            $data = SendOrderService::searchForDaliy($params, true);
            $hasShowTop = false;
            if (!$data->isEmpty()) {
                $content .= "<strong>site" . $distribution_channel_id . " 近一周数据：</strong><br/>";
                $content .= $this->getDaliyInfo($data);
                $hasShowTop = true;
            }

            $start_time = date('Y-m-d', strtotime('-3 day'));
            $end_time = date('Y-m-d');
            $params = compact('distribution_channel_id', 'start_time', 'end_time', 'promotion_type');
            $data = SendOrderService::searchForDaliy($params, true);
            if (!$data->isEmpty()) {
                if ($hasShowTop) {
                    $content .= " 不满三天数据：<br/>";
                } else {
                    $content .= "<strong>site" . $distribution_channel_id . " 不满三天数据：</strong><br/>";
                }
                $content .= $this->getDaliyInfo($data);
            }
        }
        $this->sendSendOrderEmail($content);
    }

    function getMonthTotalInfo($month, $data)
    {
        $content = "<table border='1' cellpadding='8' cellspacing='0'>
                   <tr>
                       <td align='center' nowrap='nowrap'>名称</td>
                       <td align='center' nowrap='nowrap'>点击数</td>
                       <td align='center' nowrap='nowrap'>点击人数</td>
                       <td align='center' nowrap='nowrap'>注册用户数</td>
                       <td align='center' nowrap='nowrap'>注册成本</td>
                       <td align='center' nowrap='nowrap'>付费转化率</td>
                       <td align='center' nowrap='nowrap'>新增关注</td>
                       <td align='center' nowrap='nowrap'>新增关注率</td>
                       <td align='center' nowrap='nowrap'>新关成本</td>
                       <td align='center' nowrap='nowrap'>付费用户</td>
                       <td align='center' nowrap='nowrap'>首充用户数</td>
                       <td align='center' nowrap='nowrap'>成本</td>
                       <td align='center' nowrap='nowrap'>累计充值</td>
                       <td align='center' nowrap='nowrap'>累计充值成本率</td>
                       <td align='center' nowrap='nowrap'>24小时累计充值总额</td>
                       <td align='center' nowrap='nowrap'>24小时累计充值回本率</td>
                       <td align='center' nowrap='nowrap'>72小时累计充值总额</td>
                       <td align='center' nowrap='nowrap'>72小时累计充值回本率</td>
                       <td align='center' nowrap='nowrap'>72小时充值总额</td>
                       <td align='center' nowrap='nowrap'>72小时回本率</td>
                   </tr>";

        $totalCost = 0;
        $totalFansNum = 0;
        $totalClickNum = 0;
        $totalClickUserNum = 0;
        $totalRegistNum = 0;
        $totalPayUserNum = 0;
        $total_chargeAmountIn72hours = 0;
        $total_first_recharge_user_num = 0;
        $total_promotionRegUserRechargeAmount = 0;
        $total_promotionRegUserRechargeAmountIn24hours = 0;
        $total_promotionRegUserRechargeAmountIn72hours = 0;

        foreach ($data as $item) {
            $send_order_id = $item->id;
            //点击数、点击人数、付费用户数、注册用户数、新关率、首充用户数、付费转化率、新关成本、
            $item->click_num = SendOrderService::getPv($send_order_id);
            $item->click_user_num = SendOrderService::getUv($send_order_id);
            $item->fansNum = SendOrderService::getNewFansNum($send_order_id);
            $item->pay_user_num = OrderService::getPayUserNum($send_order_id);
            $item->register_num = UserService::getPromotionTotal($send_order_id);
            $item->first_recharge_user_num = SendOrderService::getFirstChargeUserNum($send_order_id);

            $start_time = $item->send_time ? $item->send_time : $item->created_at;
            //累计充值
            $item->promotionRegUserRechargeAmount = OrderService::getPromotionRegUserRechargeAmountBySendOrerId(compact('send_order_id'));

            $end_time = date("Y-m-d H:i:s", strtotime($item->send_time) + 3 * 86400);
            //72小时充值
            $param = ['send_order_id' => $send_order_id, 'begin_time' => $item->send_time, 'end_time' => $end_time];
            $item->chargeAmountIn72hours = OrderService::getAmount($param);

            //72小时累计充值
            $param = compact('send_order_id', 'start_time', 'end_time');
            $item->promotionRegUserRechargeAmountIn72hours = OrderService::getPromotionRegUserRechargeAmountBySendOrerId($param);

            //24小时累计充值
            $end_time = date("Y-m-d H:i:s", strtotime($item->send_time) + 86400);
            $param = compact('send_order_id', 'start_time', 'end_time');
            $item->promotionRegUserRechargeAmountIn24hours = OrderService::getPromotionRegUserRechargeAmountBySendOrerId($param);

            $totalCost += $item->cost;
            $totalFansNum += $item->fansNum;
            $totalClickNum += $item->click_num;
            $totalClickUserNum += $item->click_user_num;
            $totalRegistNum += $item->register_num;
            $totalPayUserNum += $item->pay_user_num;
            $total_chargeAmountIn72hours += $item->chargeAmountIn72hours;
            $total_first_recharge_user_num += $item->first_recharge_user_num;
            $total_promotionRegUserRechargeAmount += $item->promotionRegUserRechargeAmount;
            $total_promotionRegUserRechargeAmountIn24hours += $item->promotionRegUserRechargeAmountIn24hours;
            $total_promotionRegUserRechargeAmountIn72hours += $item->promotionRegUserRechargeAmountIn72hours;
        }

        $fans_transfer = Util::getPersentAmount($totalFansNum, $totalRegistNum);
        $pay_user_transfer = Util::getPersentAmount($totalPayUserNum, $totalRegistNum);
        $chargeAmountIn72hoursCost = Util::getPersentAmount($total_chargeAmountIn72hours, $totalCost);
        $fansCost = (0 == $totalFansNum) ? $totalCost : round($totalCost / $totalFansNum, 2);
        $registCost = (0 == $totalRegistNum) ? $totalCost : round($totalCost / $totalRegistNum, 2);
        $promotionRegUserRechargeAmountCost = Util::getPersentAmount($total_promotionRegUserRechargeAmount, $totalCost);
        $promotionRegUserRechargeAmountIn24hoursCost = Util::getPersentAmount($total_promotionRegUserRechargeAmountIn24hours, $totalCost);
        $promotionRegUserRechargeAmountIn72hoursCost = Util::getPersentAmount($total_promotionRegUserRechargeAmountIn72hours, $totalCost);

        $content .=
            "<tr>
                <td align='center' nowrap='nowrap'>{$month}月推广合计</td>
                <td align='center' nowrap='nowrap'>{$totalClickNum}</td>
                <td align='center' nowrap='nowrap'>{$totalClickUserNum}</td>
                <td align='center' nowrap='nowrap'>{$totalRegistNum}</td>
                <td align='center' nowrap='nowrap'>{$registCost}</td>
                <td align='center' nowrap='nowrap'>{$pay_user_transfer}</td>
                <td align='center' nowrap='nowrap'>{$totalFansNum}</td>
                <td align='center' nowrap='nowrap'>{$fans_transfer}</td>
                <td align='center' nowrap='nowrap'>{$fansCost}</td> 
                <td align='center' nowrap='nowrap'>{$totalPayUserNum}</td>
                <td align='center' nowrap='nowrap'>{$total_first_recharge_user_num}</td>
                <td align='center' nowrap='nowrap'>{$totalCost}</td>
                <td align='center' nowrap='nowrap'>{$total_promotionRegUserRechargeAmount}</td>
                <td align='center' nowrap='nowrap'>{$promotionRegUserRechargeAmountCost}</td> 
                 <td align='center' nowrap='nowrap'>{$total_promotionRegUserRechargeAmountIn24hours}</td>
                <td align='center' nowrap='nowrap'>{$promotionRegUserRechargeAmountIn24hoursCost}</td>
                <td align='center' nowrap='nowrap'>{$total_promotionRegUserRechargeAmountIn72hours}</td>
                <td align='center' nowrap='nowrap'>{$promotionRegUserRechargeAmountIn72hoursCost}</td>
                <td align='center' nowrap='nowrap'>{$total_chargeAmountIn72hours}</td>
                <td align='center' nowrap='nowrap'>{$chargeAmountIn72hoursCost}</td>
           </tr></table>";
        return $content;
    }

    function sendSendOrderEmail($content)
    {
        $to_user = array(
             ['address' => 'yuyy@yqsd.net', 'name' => 'yuyy@yqsd.net'],
             ['address' => 'fangxq@yqsd.net', 'name' => 'fangxq@yqsd.net'],
             ['address' => 'zhangzg@yqsd.net', 'name' => 'zhangzg@yqsd.net'],
             ['address' => 'zhaojp@yqsd.net', 'name' => 'zhaojp@yqsd.net'],
             ['address' => 'huangrr@yqsd.net', 'name' => 'huangrr@yqsd.net'],
             ['address' => 'liur@iqiyoo.com', 'name' => 'liur@iqiyoo.com'],
             ['address' => 'chenzt@yqsd.net', 'name' => 'chenzt@yqsd.net'],
             ['address' => 'chenbiao@zw88.net', 'name' => 'chenbiao@zw88.net'],
             ['address' => 'hanyh@yqsd.net', 'name' => 'hanyh@yqsd.net'],
             ['address' => 'zhangrl@yqsd.net', 'name' => 'zhangrl@yqsd.net'],
             ['address' => 'caicf@zw88.net', 'name' => 'caicf@zw88.net'],
            ['address' => 'qincp@iqiyoo.com', 'name' => '阿才'],
        );
        SendStatsEmailService::SendHtmlEmailWithAcce($to_user, ['subject' => "推广组数据后台派单日报" . date("Y-m-d", time()), 'body' => $content]);
    }

    private function getDaliyInfo($data)
    {
        $content = "<table border='1' cellpadding='8' cellspacing='0'>
                   <tr>
                       <td align='center' nowrap='nowrap'>推广名称</td>
                       <td align='center' nowrap='nowrap'>预计发送时间</td>
                       <td align='center' nowrap='nowrap'>推广员</td>
                       <td align='center' nowrap='nowrap'>书名</td>
                       <td align='center' nowrap='nowrap'>类型</td>
                       <td align='center' nowrap='nowrap'>点击数</td>
                       <td align='center' nowrap='nowrap'>点击人数</td>
                       <td align='center' nowrap='nowrap'>注册用户数</td>
                       <td align='center' nowrap='nowrap'>注册成本</td>
                       <td align='center' nowrap='nowrap'>新增关注</td>
                       <td align='center' nowrap='nowrap'>新增关注率</td>
                       <td align='center' nowrap='nowrap'>新关成本</td>
                       <td align='center' nowrap='nowrap'>付费用户</td>
                       <td align='center' nowrap='nowrap'>首充用户数</td>
                       <td align='center' nowrap='nowrap'>成本</td>
                       <td align='center' nowrap='nowrap'>24小时累计充值总额</td>
                       <td align='center' nowrap='nowrap'>24小时累计充值回本率</td>
                       <td align='center' nowrap='nowrap'>72小时累计充值总额</td>
                       <td align='center' nowrap='nowrap'>72小时累计充值回本率</td>
                       <td align='center' nowrap='nowrap'>公司名称</td>
                       <td align='center' nowrap='nowrap'>备注</td>
                   </tr>";


        foreach ($data as $item) {
            $item->company_name = '';
            $item->promoter_name = '';
            $send_order_id = $item->id;
            $item->promotion_point = '';
            $distribution_channel_id = $item->distribution_channel_id;
            $channel = Channel::getChannelUserIdById($distribution_channel_id);
            if ($channel) {
                $channel_user = ChannelUser::getById($channel->channel_user_id);
                if ($channel_user) {
                    $item->company_name = $channel_user->company_name;
                }
            }

            if ($item->promotion_point == 2) {
                $item->promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $item->id;
            } else {
                $item->promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . Util::getDomainByBid($item->book_id) . '/yun/' . $item->id;
            }

            //点击数、粉丝数、付费用户数、注册用户数、新关率、首充用户数、付费转化率、新关成本、
            $item->click_num = SendOrderService::getPv($send_order_id);
            $item->click_user_num = SendOrderService::getUv($send_order_id);
            $item->fansNum = SendOrderService::getNewFansNum($send_order_id);
            $item->pay_user_num = OrderService::getPayUserNum($send_order_id);

            $item->register_num = UserService::getPromotionTotal($send_order_id);
            $item->fans_transfer = Util::getPersentAmount($item->fansNum, $item->register_num);
            $item->first_recharge_user_num = SendOrderService::getFirstChargeUserNum($send_order_id);
            $item->pay_user_transfer = Util::getPersentAmount($item->pay_user_num, $item->register_num);
            $item->fansNumCost = (0 == $item->fansNum) ? $item->cost : round(($item->cost / $item->fansNum), 2);

            $start_time = $item->send_time ? $item->send_time : $item->created_at;
            //累计充值、累计充值成本率
            $item->promotionRegUserRechargeAmount = OrderService::getPromotionRegUserRechargeAmountBySendOrerId(compact('send_order_id'));
            $item->promotionRegUserRechargeAmountCost = Util::getPersentAmount($item->promotionRegUserRechargeAmount, $item->cost);
            $end_time = date("Y-m-d H:i:s", strtotime($item->send_time) + 3 * 86400);

            //72小时充值、72小时充值回本率
            $item->chargeAmountIn72hours = OrderService::getAmount(['send_order_id' => $send_order_id, 'begin_time' => $item->send_time, 'end_time' => $end_time]);
            $item->chargeAmountIn72hoursCost = Util::getPersentAmount($item->chargeAmountIn72hours, $item->cost);

            //72小时累计充值、72小时累计充值回本率
            $item->promotionRegUserRechargeAmountIn72hours = OrderService::getPromotionRegUserRechargeAmountBySendOrerId(compact('send_order_id', 'start_time', 'end_time'));
            $item->promotionRegUserRechargeAmountIn72hoursCost = Util::getPersentAmount($item->promotionRegUserRechargeAmountIn72hours, $item->cost);

            //24小时累计充值、24小时累计充值回本率
            $end_time = date("Y-m-d H:i:s", strtotime($item->send_time) + 86400);
            $item->promotionRegUserRechargeAmountIn24hours = OrderService::getPromotionRegUserRechargeAmountBySendOrerId(compact('send_order_id', 'start_time', 'end_time'));
            $item->promotionRegUserRechargeAmountIn24hoursCost = Util::getPersentAmount($item->promotionRegUserRechargeAmountIn24hours, $item->cost);

            //代理商、推广渠道
            $agentInfo = AgentServices::getAgentByChannelId($item->distribution_channel_id);
            $item->agent_name = $agentInfo ? $agentInfo->agent_name : '';
            $item->promotion_channel = $agentInfo ? $agentInfo->agent_intro : '';

            //注册成本
            $item->register_cost = (0 == $item->register_num) ? $item->cost : round(($item->cost / $item->register_num), 2);
            if (strpos($item->name, "-")) {
                $strs = explode('-', $item->name);
                $item->name = $strs[0];
                if (count($strs) == 4) {
                    $item->promoter_name = $strs[3];
                    if (!$item->pre_send_date) {
                        $item->pre_send_date = Util::getFormatDate($strs[2], $item->created_at);
                    }
                } elseif (count($strs) == 6) {
                    $item->promoter_name = $strs[5];
                    if (!$item->pre_send_date) {
                        $item->pre_send_date = Util::getFullDate($strs[2], $strs[3], $strs[4], $item->created_at);
                    }
                }
            }
            $book_type = $this->getBookType($item->book_id);
            $content .=
                "<tr>
                <td align='center' nowrap='nowrap'>{$item->name}</td>
                <td align='center' nowrap='nowrap'>{$item->pre_send_date}</td>
                <td align='center' nowrap='nowrap'>{$item->promoter_name}</td>
                <td align='center' nowrap='nowrap'>{$item->book_name}</td>
                <td align='center' nowrap='nowrap'>{$book_type}</td>
                <td align='center' nowrap='nowrap'>{$item->click_num}</td>
                <td align='center' nowrap='nowrap'>{$item->click_user_num}</td>
                <td align='center' nowrap='nowrap'>{$item->register_num}</td>
                <td align='center' nowrap='nowrap'>{$item->register_cost}</td>
                <td align='center' nowrap='nowrap'>{$item->fansNum}</td> 
                <td align='center' nowrap='nowrap'>{$item->fans_transfer}</td>
                <td align='center' nowrap='nowrap'>{$item->fansNumCost}</td>
                <td align='center' nowrap='nowrap'>{$item->pay_user_num}</td>
                <td align='center' nowrap='nowrap'>{$item->first_recharge_user_num}</td>
                <td align='center' nowrap='nowrap'>{$item->cost}</td> 
                 <td align='center' nowrap='nowrap'>{$item->promotionRegUserRechargeAmountIn24hours}</td>
                <td align='center' nowrap='nowrap'>{$item->promotionRegUserRechargeAmountIn24hoursCost}</td>
                <td align='center' nowrap='nowrap'>{$item->promotionRegUserRechargeAmountIn72hours}</td>
                <td align='center' nowrap='nowrap'>{$item->promotionRegUserRechargeAmountIn72hoursCost}</td>
                <td align='center' nowrap='nowrap'>{$item->import_company_name}</td>
                <td align='center' nowrap='nowrap'>{$item->remark}</td>
                </tr>";
        }
        $content .= "</table>";
        return $content;
    }

    public function getBookType($book_id)
    {
        $book_type = '';
        if ($book_id) {
            $bookConfig = BookConfig::getBookById($book_id);
            if ($bookConfig) {
                if ($bookConfig->charge_type == 'CHAPTER') {
                    $book_type = '长篇';
                } else if ($bookConfig->charge_type == 'BOOK') {
                    $book_type = '短篇';
                }
            }
        }
        return $book_type;
    }
}